package com.ruoyi.analyse.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruoyi.analyse.domain.QuestionAnalysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.analyse.mapper.ChatMessageMapper;
import com.ruoyi.analyse.domain.ChatMessage;
import com.ruoyi.analyse.service.IChatMessageService;
import com.ruoyi.analyse.service.IQuestionAnalysisService;
import com.ruoyi.analyse.service.IStudentProfileService;

/**
 * 聊天记录Service业务层处理
 *
 * @author ruoyi
 */
@Service
public class ChatMessageServiceImpl implements IChatMessageService
{
    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private IQuestionAnalysisService questionAnalysisService;

    @Autowired
    private IStudentProfileService studentProfileService;


    /**
     * 查询聊天记录
     *
     * @param xxId 聊天记录主键
     * @return 聊天记录
     */
    @Override
    public ChatMessage selectChatMessageByXxId(Long xxId)
    {
        return chatMessageMapper.selectChatMessageByXxId(xxId);
    }

    /**
     * 查询聊天记录列表
     *
     * @param chatMessage 聊天记录
     * @return 聊天记录集合
     */
    @Override
    public List<ChatMessage> selectChatMessageList(ChatMessage chatMessage)
    {
        return chatMessageMapper.selectChatMessageList(chatMessage);
    }

    /**
     * 根据会话ID获取完整对话
     *
     * @param ltId 会话ID
     * @return 聊天记录列表
     */
    @Override
    public List<ChatMessage> getConversationByLtId(String ltId)
    {
        ChatMessage query = new ChatMessage();
        query.setLtId(ltId);
        List<ChatMessage> messages = chatMessageMapper.selectChatMessageList(query);

        // 根据创建时间升序排序，确保对话顺序正确
        messages.sort((m1, m2) -> m1.getCreateTime().compareTo(m2.getCreateTime()));

        return messages;
    }

    /**
     * 获取用户的所有提问
     *
     * @param userName 用户名
     * @return 用户提问列表
     */
    @Override
    public List<ChatMessage> getUserQuestions(String userName)
    {
        ChatMessage query = new ChatMessage();
        query.setUserName(userName);
        query.setRole("user");  // 只查询用户的提问
        return chatMessageMapper.selectChatMessageList(query);
    }

    /**
     * 分析最近问题趋势
     *
     * @param days 天数
     * @return 每日问题统计
     */
    @Override
    public List<Map<String, Object>> getDailyQuestionStatistics(int days, Long classId)
    {
        List<Map<String, Object>> dailyStats = chatMessageMapper.countDailyQuestions(days, classId);
        List<Map<String, Object>> result = new ArrayList<>();

        // 如果结果为空，创建默认数据
        if (dailyStats == null || dailyStats.isEmpty()) {
            for (int i = 0; i < days; i++) {
                Map<String, Object> stat = new HashMap<>();
                Date date = new Date(System.currentTimeMillis() - (days - i - 1) * 86400000L);
                stat.put("date", date);
                stat.put("count", 0);
                result.add(stat);
            }
        } else {
            // 统一处理数据格式
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            for (Map<String, Object> stat : dailyStats) {
                Map<String, Object> item = new HashMap<>();
                String dayStr = (String) stat.get("day");
                try {
                    Date date = format.parse(dayStr);
                    item.put("date", date);
                    item.put("count", stat.get("count"));
                    result.add(item);
                } catch (ParseException e) {
                    // 跳过无效日期
                    continue;
                }
            }
        }

        return result;
    }


    /**
     * 处理新问题并进行分析
     *
     * @param chatMessage 聊天消息
     * @return 处理结果
     */
    @Override
    public Map<String, Object> processAndAnalyzeQuestion(ChatMessage chatMessage)
    {
        Map<String, Object> result = new HashMap<>();

        // 只处理学生的提问消息
        if (!"user".equals(chatMessage.getRole())) {
            result.put("success", false);
            result.put("message", "只能处理学生提问消息");
            return result;
        }

        String content = chatMessage.getXxContent();
        String userName = chatMessage.getUserName();
        Long classId = chatMessage.getClassId();

        try {
            // 1. 提取关键词
            List<String> keywords = extractKeywords(content);

            // 2. 识别学科分类
            String subject = identifySubject(content);

            // 3. 评估问题复杂度
            String complexity = evaluateComplexity(content);

            // 4. 识别问题类型
            String questionType = identifyQuestionType(content);

            // 5. 更新问题分析统计 - 这里是关键修改点
            for (String keyword : keywords) {
                // 直接调用问题分析服务更新统计信息
                QuestionAnalysis qa = new QuestionAnalysis();
                qa.setKeyword(keyword);
                qa.setSubject(subject);
                qa.setQuestionType(questionType);
                qa.setComplexity(complexity);
                qa.setFrequency(1); // 初始频次为1
                qa.setCreateTime(new Date());
                qa.setUpdateTime(new Date());
                qa.setClassId(classId);
                qa.setUserName(userName);

                // 先查询是否存在该关键词和学科组合
                QuestionAnalysis existingQa = questionAnalysisService.selectQuestionAnalysisByKeywordAndSubject(keyword, subject);

                if (existingQa != null) {
                    // 更新已有记录
                    existingQa.setFrequency(existingQa.getFrequency() + 1);
                    existingQa.setUpdateTime(new Date());
                    questionAnalysisService.updateQuestionAnalysis(existingQa);
                } else {
                    // 新增记录
                    questionAnalysisService.insertQuestionAnalysis(qa);
                }
            }

            // 6. 更新学生学情画像
            studentProfileService.updateStudentQuestionRecord(userName, subject, complexity);

            // 7. 构建返回结果
            result.put("success", true);
            result.put("keywords", keywords);
            result.put("subject", subject);
            result.put("complexity", complexity);
            result.put("questionType", questionType);

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "处理问题时出错: " + e.getMessage());
            e.printStackTrace(); // 确保错误被记录
        }

        return result;
    }


    /**
     * 提取关键词
     *
     * @param content 内容
     * @return 关键词列表
     */
    private List<String> extractKeywords(String content) {
        List<String> keywords = new ArrayList<>();

        // 计算机专业关键词词库 - 实际应用中可以从配置文件或数据库加载
        String[] techKeywords = {
            "Java", "Python", "C\\+\\+", "数据结构", "算法", "数据库", "SQL", "操作系统",
            "网络", "编程", "开发", "框架", "前端", "后端", "web", "人工智能", "机器学习",
            "深度学习", "计算机网络", "网络安全", "软件工程", "代码", "bug", "调试", "测试",
            "运行", "编译", "系统", "架构", "设计模式", "API", "接口", "类", "对象", "函数",
            "方法", "变量", "Spring", "SpringBoot", "Vue", "React", "Angular", "数据分析",
            "大数据", "云计算", "微服务", "容器", "Docker", "Linux", "Windows", "服务器"
        };

        // 使用正则表达式匹配关键词
        for (String keyword : techKeywords) {
            Pattern pattern = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(content);
            if (matcher.find()) {
                keywords.add(keyword);
            }
        }

        // 如果没有匹配到关键词,取前5个字作为关键词
        if (keywords.isEmpty() && content.length() > 5) {
            keywords.add(content.substring(0, Math.min(5, content.length())));
        }

        return keywords;
    }

    /**
     * 识别学科分类
     *
     * @param content 内容
     * @return 学科分类
     */
    private String identifySubject(String content) {
        // 学科关键词映射 - 可以从配置或数据库加载
        Map<String, String> subjectKeywords = new HashMap<>();
        subjectKeywords.put("数据结构", "数据结构与算法");
        subjectKeywords.put("算法", "数据结构与算法");
        subjectKeywords.put("链表", "数据结构与算法");
        subjectKeywords.put("树", "数据结构与算法");
        subjectKeywords.put("图", "数据结构与算法");
        subjectKeywords.put("排序", "数据结构与算法");

        subjectKeywords.put("Java", "编程语言");
        subjectKeywords.put("Python", "编程语言");
        subjectKeywords.put("C++", "编程语言");
        subjectKeywords.put("JavaScript", "编程语言");
        subjectKeywords.put("变量", "编程语言");
        subjectKeywords.put("函数", "编程语言");

        subjectKeywords.put("数据库", "数据库系统");
        subjectKeywords.put("SQL", "数据库系统");
        subjectKeywords.put("MySQL", "数据库系统");
        subjectKeywords.put("Oracle", "数据库系统");
        subjectKeywords.put("表", "数据库系统");
        subjectKeywords.put("查询", "数据库系统");

        subjectKeywords.put("操作系统", "操作系统");
        subjectKeywords.put("Linux", "操作系统");
        subjectKeywords.put("Windows", "操作系统");
        subjectKeywords.put("进程", "操作系统");
        subjectKeywords.put("线程", "操作系统");
        subjectKeywords.put("内存", "操作系统");

        subjectKeywords.put("网络", "计算机网络");
        subjectKeywords.put("TCP", "计算机网络");
        subjectKeywords.put("IP", "计算机网络");
        subjectKeywords.put("HTTP", "计算机网络");
        subjectKeywords.put("协议", "计算机网络");

        subjectKeywords.put("前端", "Web开发");
        subjectKeywords.put("HTML", "Web开发");
        subjectKeywords.put("CSS", "Web开发");
        subjectKeywords.put("Javascript", "Web开发");
        subjectKeywords.put("Vue", "Web开发");
        subjectKeywords.put("React", "Web开发");

        subjectKeywords.put("后端", "系统开发");
        subjectKeywords.put("框架", "系统开发");
        subjectKeywords.put("Spring", "系统开发");
        subjectKeywords.put("SpringBoot", "系统开发");
        subjectKeywords.put("接口", "系统开发");
        subjectKeywords.put("API", "系统开发");

        subjectKeywords.put("人工智能", "人工智能");
        subjectKeywords.put("机器学习", "人工智能");
        subjectKeywords.put("深度学习", "人工智能");
        subjectKeywords.put("神经网络", "人工智能");

        subjectKeywords.put("软件工程", "软件工程");
        subjectKeywords.put("设计模式", "软件工程");
        subjectKeywords.put("测试", "软件工程");
        subjectKeywords.put("项目管理", "软件工程");

        // 默认学科
        String subject = "其他";

        // 判断内容中是否包含学科关键词
        for (Map.Entry<String, String> entry : subjectKeywords.entrySet()) {
            if (content.toLowerCase().contains(entry.getKey().toLowerCase())) {
                subject = entry.getValue();
                break;
            }
        }

        return subject;
    }

    /**
     * 评估问题复杂度
     *
     * @param content 内容
     * @return 复杂度评级
     */
    private String evaluateComplexity(String content) {
        // 简单规则: 问题长度 + 特定关键词判断
        int length = content.length();
        boolean hasComplexTerms = content.matches(".*(如何|为什么|原理|实现|设计|比较|分析).*");
        boolean hasCodeRequest = content.matches(".*(代码|编程|程序|实现|写一个).*");

        if (length > 100 || (length > 50 && hasComplexTerms) || (hasCodeRequest && hasComplexTerms)) {
            return "COMPLEX";
        } else if (length > 30 || hasComplexTerms || hasCodeRequest) {
            return "MEDIUM";
        } else {
            return "SIMPLE";
        }
    }

    /**
     * 识别问题类型
     *
     * @param content 内容
     * @return 问题类型
     */
    private String identifyQuestionType(String content) {
        if (content.matches(".*(什么是|概念|定义|介绍).*")) {
            return "概念解释";
        } else if (content.matches(".*(如何|怎么|怎样|步骤|方法).*")) {
            return "操作指导";
        } else if (content.matches(".*(为什么|原因|解释|分析).*")) {
            return "原理分析";
        } else if (content.matches(".*(区别|比较|不同).*")) {
            return "比较分析";
        } else if (content.matches(".*(代码|程序|编写|实现).*")) {
            return "代码实现";
        } else if (content.matches(".*(错误|问题|bug|异常|失败).*")) {
            return "错误诊断";
        } else if (content.matches(".*(优化|提高|改进).*")) {
            return "优化建议";
        } else {
            return "一般提问";
        }
    }

    /**
     * 处理历史问题数据
     *
     * @return 处理的记录数
     */
    @Override
    public int processHistoryData() {
        // 创建查询对象
        ChatMessage query = new ChatMessage();
        query.setRole("user"); // 只处理用户的提问

        // 查询所有用户提问记录
        List<ChatMessage> userMessages = chatMessageMapper.selectChatMessageList(query);
        int count = 0;

        for (ChatMessage message : userMessages) {
            try {
                // 处理每条记录
                processAndAnalyzeQuestion(message);
                count++;
            } catch (Exception e) {
                // 记录错误但继续处理下一条
                System.out.println("处理历史记录失败，ID: " + message.getXxId()+ e);
            }
        }

        return count;
    }

}
